package com.zhanghe.study.io.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @author: zhanghe
 * @date: 2020/6/16 10:43
 */
public class GetChannel {
    private static final String FILE = "C:\\Users\\sinosoft\\Desktop\\剩余工作副本.txt";
    public static void main(String[] args) {
        //生成FileChannel文件通道  FileChannel的操作--> 操作ByteBuffer用于读写，并独占式访问和锁定文件区域
        byte[] bytes;

        ByteBuffer bb = ByteBuffer.allocate(32);
        IntBuffer ib = bb.asIntBuffer();
        // 保存 int 数组：
        ib.put(new int[]{ 11, 42, 47, 99, 143, 811, 1016 });
        ib.rewind();
        while(ib.hasRemaining()){
            ib.mark();
            System.out.println("获取position"+ib.position());
            System.out.println("值为"+ib.get());
        }
        //绝对位置读写：
//        System.out.println(ib.get(3));
        ib.put(3, 1811);
        // 在重置缓冲区前设置新的限制

        ib.flip();
        while(ib.hasRemaining()) {
            int i = ib.get();
            System.out.println(i);
        }

        try {
            FileChannel.open(Paths.get(FILE), StandardOpenOption.READ,StandardOpenOption.CREATE,StandardOpenOption.WRITE);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 写入文件
        try(FileChannel fileChannel = new FileOutputStream(FILE).getChannel()){
            fileChannel.write(ByteBuffer.wrap("test".getBytes()));
        } catch (IOException e){
            throw new RuntimeException("写入文件失败",e);
        }
        // 在文件结尾写入
        try(FileChannel fileChannel = new RandomAccessFile(FILE,"rw").getChannel()){
            fileChannel.position(fileChannel.size());//移至文件结尾
            fileChannel.write(ByteBuffer.wrap("some".getBytes()));
        } catch (IOException e){
            throw new RuntimeException("写入文件结尾失败",e);
        }

        try(FileChannel fileChannel = new FileInputStream(FILE).getChannel();
            FileChannel out = new FileOutputStream("C:\\Users\\sinosoft\\Desktop\\copy.txt").getChannel()
        ){
            // 读取操作，需要调用allocate显示分配ByteBuffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // read之后将数据放入缓冲区
            while (fileChannel.read(byteBuffer) != -1){
                byteBuffer.flip(); // 准备写入
                out.write(byteBuffer);
                byteBuffer.clear(); // 清空缓存区
            }
        } catch (IOException e){
            throw new RuntimeException("读取文件失败",e);
        }
    }
}
